import {NgForm} from "@angular/forms";
import {Logger} from "../../utils";
import {SupportLanguage} from '../../models/common/support-language';
import {CookieHelper} from '../../utils';
import {environment} from '../../../../environments/environment';
import {PlatformHelper} from '../../utils/platform-helper';

export class BaseComponent {
  isLoading: boolean = true;
  errorMessage: string;
  isSubmitting: boolean = false;
  isPreparingSubmitData: boolean = false;
  isValidating: boolean = false;
  dataChanged: boolean = false;
  _objectSnapshot: string;
  hasLoggedIn: boolean = CookieHelper.hasLoggedIn();
  isSearching: boolean;
  currentUserId: string = CookieHelper.get(environment.userIdCookieKey);

  protected validate(form: NgForm): boolean {
    if (!form) {
      return false;
    }

    this.isValidating = true;
    for (const controlName in form.controls) {
      const formControl = form.controls[controlName];

      formControl.markAsTouched();
      formControl.markAsDirty();

      if (!formControl.valid) {
        Logger.log(`Invalid field: ${controlName}, errors: ${JSON.stringify(formControl.errors)}`);
      }
    }

    Logger.log(`form.valid: ${form.valid}`);

    this.isValidating = false;
    return form.valid;
  }

  hasChanges(): boolean {
    return this.dataChanged;
  }

  setDataChanged(changed: boolean): void {
    this.dataChanged = changed;
  }

  snapshot(object: any): void {
    this._objectSnapshot = JSON.stringify(object);
  }

  hasObjectChanged(object: any): boolean {
    let origin = JSON.stringify(object);
    let changed = origin !== this._objectSnapshot;
    Logger.log(`Detect object changes: ${changed}\n[Origin]\n${this._objectSnapshot}\n[Current]\n${origin}`);

    return changed;
  }

  getActiveLanguage(): string {
    return environment.activeLanguage;
  }

  submitCompleted(): void {
    this.isSubmitting = false;
    this.isPreparingSubmitData = false;
  }

  isMobileMode(): boolean {
    return PlatformHelper.isMobileMode();
  }

  isEnglish(): boolean {
    return this.getActiveLanguage() == SupportLanguage.en_us;
  }

  isPresent(value: any): boolean {
    return !!value;
  }

  stopPropagation(event: Event): void {
    event.stopPropagation();
    // event.preventDefault();
  }
}
